<template>
  <div class="article-container">
    <!-- 文章列表 -->
    <van-pull-refresh v-model="isLoading" :success-duration="1000" :success-text="successText" @refresh="onRefresh">
    <van-list
      v-model="loading"
      :finished="finished"
      finished-text="没有更多了"
      :error.sync="error"
      error-text="请求失败，点击重新加载"
      @load="onLoad"
    >
      <!-- <van-cell v-for="item in articleList" :key="item.ch_id" :title="item.title" /> -->
      <article-item :articleListItem="item" v-for="(item, index) in articleList" :key="index"></article-item>
    </van-list>
    </van-pull-refresh>
  </div>
</template>

<script>
import { getArticle } from '@/api/articleList'
import articleItem from '@/components/articleItem'
export default {
  data () {
    return {
      articleList: [], // 列表数据
      loading: false, // 是否显示加载
      finished: false, // 是否显示没有更多数据提示
      pre_timestamp: null, // 下一页时间戳
      error: false, // 错误加载flag
      isLoading: false, // 下拉刷新
      successText: ''
    }
  },
  props: {
    channels: {
      type: Object,
      required: true
    }
  },
  components: {
    articleItem
  },
  methods: {
    // 获取文章列表
    async onLoad () {
      try {
        const { data: res } = await getArticle({
          channel_id: this.channels.id,
          timestamp: this.pre_timestamp || +new Date(),
          with_top: 1
        })
        // 返回数据中解构出 数据  和下一页时间戳
        const { results, pre_timestamp: preTime } = res.data
        // 不能直接赋值覆盖, 需展开push到数据中
        this.articleList.push(...results)
        this.loading = false
        if (results.length) {
          this.pre_timestamp = preTime
        } else {
          this.finished = true
        }
      } catch (err) {
        this.error = true
        this.loading = false
        console.log('请求失败')
      }
    },
    // 下拉刷新
    async onRefresh () {
      try {
        const { data: res } = await getArticle({
          channel_id: this.channels.id,
          timestamp: +new Date(),
          with_top: 1
        })
        console.log(2)
        this.articleList.unshift(...res.data.results)
        this.isLoading = false
        this.successText = `刷新成功,共加载了${res.data.results.length}条数据!`
      } catch (e) {
        this.isLoading = false
        this.successText = '加载失败'
      }
    }
  }
}
</script>

<style scoped lang="less">
.article-container {
  height: 80vh;
  overflow: scroll;
}
</style>
